import { _decorator, Component, instantiate, Prefab, RigidBody, Node, Vec3, ParticleSystem } from 'cc';
import { Databus } from '../core/Databus';
import { Game } from '../core/Game';
import { EventManager } from '../core/EventManager';
import { BilliardGame } from './BilliardGame';
import { TableAtrribute } from '../core/TableAttribute';
const { ccclass, property } = _decorator;

const databus = Databus.Instance();
@ccclass('TableController')
export class TableController extends Component {
  // 球桌的预制件[默认，高端，奢华，完美]
  @property(Prefab)
  DefaultTable: Prefab = null;
  @property(Prefab)
  HighLevelTable: Prefab = null;
  @property(Prefab)
  LuxuryTable: Prefab = null;
  @property(Prefab)
  PerfectTable: Prefab = null;
  private table: Node = null;

  protected onLoad(): void {
    const tableName = Game.Instance().outlookAttribute.table.tableName;
    if (tableName === "HighLevelTable") {
      this.table = instantiate(this.HighLevelTable);
      this.updateTable(this.table);
    } else if (tableName === "LuxuryTable") {
      this.table = instantiate(this.LuxuryTable);
      this.updateTable(this.table);
    } else if (tableName === "PerfectTable") {
      this.table = instantiate(this.PerfectTable);
      this.updateTable(this.table);
    } else {
      this.table = instantiate(this.DefaultTable);
      this.updateTable(this.table);
    }
    this.initTableCollision();
  }
  public getDeskBallHolePosition() {
    return [
      this.table.getChildByName('BallHole1').worldPosition,
      this.table.getChildByName('BallHole2').worldPosition,
      this.table.getChildByName('BallHole3').worldPosition,
      this.table.getChildByName('BallHole4').worldPosition,
      this.table.getChildByName('BallHole5').worldPosition,
      this.table.getChildByName('BallHole6').worldPosition,
    ];
  }
  public getDeskHolePosition() {
    return [
      this.table.getChildByName('DeskHole1').worldPosition,
      this.table.getChildByName('DeskHole2').worldPosition,
      this.table.getChildByName('DeskHole3').worldPosition,
      this.table.getChildByName('DeskHole4').worldPosition,
      this.table.getChildByName('DeskHole5').worldPosition,
      this.table.getChildByName('DeskHole6').worldPosition,
    ];
  }
  
  public initTableCollision() {
    const deskEdge = this.table.getChildByName('DeskEdge');
    const deskEdgeBody = deskEdge.getComponent(RigidBody);
    deskEdgeBody.useCCD = true;

    const deskCornerHole = this.table.getChildByName('DeskCornerHole');
    const deskCornerBody = deskCornerHole.getComponent(RigidBody);
    deskCornerBody.useCCD = true;

    const deskCenterHole = this.table.getChildByName('DeskCenterHole');
    const deskCenterBody = deskCenterHole.getComponent(RigidBody);
    deskCenterBody.useCCD = true;
  }

  // 插件更新节点
  public updateTable(tableNode: Node) {
    const tables = this.node;
    for (const tb of tables.children) { tb.destroy(); }
    tableNode.setParent(this.node);
    tableNode.active = true;
  }
}

